<?php
/**
 * author: yunshu
 * createTime: 18/2/23 16:05
 * description:
 */

namespace app\api\controller\v1;

use app\common\model\Order as OrderModel;
use app\common\service\Order as OrderService;
use app\api\controller\Base;
use app\common\service\Token as TokenService;
use app\common\validate\IdValidate;
use app\common\validate\OrderPalceValidate;
use app\common\validate\PagingParameterValidate;
use app\library\exception\OrderException;

class Orders extends Base
{
    protected $beforeActionList = [
            'checkExclusiveScope' => ['only' => 'create'],
            'checkSuperScope'     => ['only' =>  'getSummary'],
            'checkPrimaryScope'   => ['only' => 'read'],
        ];

    public function create()
    {
        (new OrderPalceValidate())->checkValidate();

        $products = input('post.products/a');
        $uid = TokenService::getCurrentUid();

        $ret = (new OrderService())->place($uid, $products);

        return api_json($ret, EC_OK, 'successful', 201);
    }

    public function getSummary($page, $size)
    {
        (new PagingParameterValidate())->checkValidate();

        $data = OrderModel::instance()->getSummary($page, $size);

        return $data;
    }

    public function getSummaryByUser($page, $size)
    {
        (new PagingParameterValidate())->checkValidate();

        $uid = TokenService::getCurrentTokenVar('uid');
        $data = OrderModel::instance()->getSummaryByUser($uid, $page, $size);

        return $data;
    }

    public function read($id)
    {
        (new IdValidate())->checkValidate();

        $data = OrderModel::find($id);
        if (! $data) {
            throw new OrderException();
        }

        return $data;
    }
}